package com.demo.controller;


import com.demo.exception.LoginException;
import com.demo.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author author
 * @since 2023-02-23
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class SysUserController {



    @Autowired
    private ISysUserService userService;

    /**
     * 方法说明: 登录
     *
     * @param email    邮箱
     * @param password 密码
     * @return java.lang.String
     * @version v1.0
     * @author 梁阿龙
     * @date 2023-02-24 10:38
     */
    @PostMapping("/login")
    @ResponseBody
    public HashMap<String,String> login(String email, String password ){
        HashMap<String, String> map = new HashMap<String, String>();
        /*获取subject */
        Subject subject = SecurityUtils.getSubject();
        /*封装token */
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        /* 调用登录方法 */
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            map.put("error", e.getMessage());
            map.put("code", "1002");
            map.put("message", "账号不存在");
            log.info("账号不存在");
            return map;
        }catch (IncorrectCredentialsException e){
            map.put("error", e.getMessage());
            map.put("code", "1003");
            map.put("message", "密码错误");
            log.info("密码错误");
            return map;
        }
        map.put("code", "1000");
        map.put("message", "登录成功");
        log.info("登录成功");
        return map;
    }



    /**
     * 方法说明: 注册
     * @param username
     * @param email
     * @param password
     * @return java.lang.String
     * @version v1.0
     * @author 梁阿龙
     * @date 2023-02-24 11:06*/
    @PostMapping ("register")
    @ResponseBody
    public HashMap<String,String> register(String username , String email , String password ){
        HashMap<String, String> map = new HashMap<>();
        try {
            userService.register(username, email, password);
        }catch (Exception e){
            map.put("error", e.getMessage());
            map.put("code", "1001");
            map.put("message", "注册失败");
            log.error("注册失败");
            return map;
        }
        map.put("code", "1000");
        map.put("message", "注册成功");
        log.info("注册成功");
        return map;
    }

}
